import Vue from 'vue';
import DragDialog from './drag-dialog.vue';
import router from '@/router';
import store from '@/store';

let instance;
const DragDialogInstance = Vue.extend(DragDialog);

const initInstance = (options) => {
  const components = {};
  if (options.component) {
    components.dynamicComp = options.component;
    delete options.component;
  }
  instance = new DragDialogInstance({
    data: {
      ...options,
    },
    components,
    // 由于通过 vue.extend 创建的子类无法访问父类的 store、router、i18n 等属性或方法，所以需要在此处重新实例化
    router,
    store,
  });

  document.body.appendChild(instance.$mount().$el);
};

const dragDialogComp = (options = {}) => {
  if (!instance) {
    initInstance(options); // 未挂载进行挂载
  } else {
    // 实例化后 instance 就是一个对象了，所以data内的数据会挂载到 this 下，传入一个对象与之合并
    Object.assign(instance, options);
  }

  return instance.show(vm => {
    instance = null;  // 将实例对象清空
  });
};

const plugin = {
  install(app, options = {}) {
    app.prototype.$dynamicModal = dragDialogComp;
  },
};

export default plugin;
